package cj.web.tb.controllers;

import java.io.File;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.web.admin.constants.Constants;
import cj.web.admin.constants.UserTypeEnum;
import cj.web.admin.dao.UserInfoDAO;
import cj.web.admin.domain.UserInfo;
import cj.web.admin.utils.ReadConfigProperties;
import cj.web.admin.utils.ReturnUUID;
import cj.web.login.controllers.BaseController;
import cj.web.tb.constants.RaterTypeEnum;
import cj.web.tb.constants.StatusEnum;
import cj.web.tb.dao.TBRaterRegistrationDAO;
import cj.web.tb.domain.TBRaterRegistration;

@Path("/tBRater")
public class TBRaterRegistrationController extends BaseController{

	private static Logger logger = Logger.getLogger(TBRaterRegistrationController.class.getName());
	
	@Autowired
	private TBRaterRegistrationDAO tBRaterRegistrationDao;
	@Autowired
	private UserInfoDAO userInfoDao;
	
	@Get("showxx")
	public String showxx(Model model,TBRaterRegistration tBRaterRegistration) {
		return "/views/tb/raterxxList.vm";
	}

	@Post("getxxList")
	public String queryxxList(TBRaterRegistration tBRaterRegistration,HttpServletRequest request) {
		//当前页  
		tBRaterRegistration.setStart((tBRaterRegistration.getPage()-1)*tBRaterRegistration.getRows());
		tBRaterRegistration.setLength(tBRaterRegistration.getRows());
		
		JSONObject jo = new JSONObject();
		//专家用户ID
		tBRaterRegistration.setUserId(returnSessionObj(request).getId());
		List<TBRaterRegistration> objs = tBRaterRegistrationDao.queryByUserId(tBRaterRegistration);
		
		for(TBRaterRegistration obj:objs){
			obj.setTypeName(RaterTypeEnum.getName(obj.getType()));
			obj.setStatusName(StatusEnum.getName(obj.getStatus()));
		}
		
		int size = tBRaterRegistrationDao.queryByUserIdSize(tBRaterRegistration);
		jo.put("rows", objs);
		jo.put("total", size);
		return "@"+jo.toString();
	}
	//--------------------------------------------------------------------------
	
	@Get("show")
	public String show(Model model,TBRaterRegistration tBRaterRegistration) {
		return "/views/tb/raterList.vm";
	}

	@Post("getList")
	public String queryList(TBRaterRegistration tBRaterRegistration) {
		//当前页  
		tBRaterRegistration.setStart((tBRaterRegistration.getPage()-1)*tBRaterRegistration.getRows());
		tBRaterRegistration.setLength(tBRaterRegistration.getRows());
		
		JSONObject jo = new JSONObject();
		
		List<TBRaterRegistration> objs = tBRaterRegistrationDao.query(tBRaterRegistration);
		
		for(TBRaterRegistration obj:objs){
			obj.setTypeName(RaterTypeEnum.getName(obj.getType()));
			obj.setStatusName(StatusEnum.getName(obj.getStatus()));
		}
		
		int size = tBRaterRegistrationDao.querySize(tBRaterRegistration);
		jo.put("rows", objs);
		jo.put("total", size);
		return "@"+jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model){
		model.add("typelis",EnumSet.allOf(RaterTypeEnum.class));
		return "/views/tb/raterDetail.vm";
	}
	
	@Post("create")
	public String create(Model model,TBRaterRegistration tBRaterRegistration,@Param("uploadimage") MultipartFile file,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			
			UserInfo userInfo = new UserInfo();
			userInfo.setAccount(tBRaterRegistration.getAccount());
			userInfo.setName(tBRaterRegistration.getAccount());
			userInfo.setPwd(tBRaterRegistration.getPwd());
			userInfo.setType(UserTypeEnum.teacher.getValue());
			userInfo.setState(Constants.portal.userState.state_0);
			userInfo.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
			userInfo.setCreateUser(returnSessionObj(request).getAccount());
			userInfo.setUpdateUser(returnSessionObj(request).getAccount());
			int userId = userInfoDao.create(userInfo);
			
			// 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
	                // 转存文件  
	                file.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                tBRaterRegistration.setPhoto(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
	        tBRaterRegistration.setUserId(userId);
	        tBRaterRegistration.setStatus(StatusEnum.TYPE1.getValue());
			tBRaterRegistration.setCreateUser(returnSessionObj(request).getAccount());
			tBRaterRegistration.setUpdateUser(returnSessionObj(request).getAccount());
			tBRaterRegistrationDao.create(tBRaterRegistration);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("edit")
	public String edit(Model model,@Param("id") int id)
	{
		TBRaterRegistration obj = tBRaterRegistrationDao.queryById(id);
		
		UserInfo userInfo = userInfoDao.queryById(obj.getUserId());
		
		model.add("typelis",EnumSet.allOf(RaterTypeEnum.class));
		model.add("obj", obj);
		model.add("userInfo", userInfo);
		return "/views/tb/raterEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,TBRaterRegistration tBRaterRegistration,@Param("uploadimage") MultipartFile file,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			
			UserInfo userInfo = new UserInfo();
			userInfo.setId(tBRaterRegistration.getUserId());
			userInfo.setName(tBRaterRegistration.getAccount());
			userInfo.setType(UserTypeEnum.teacher.getValue());
			userInfo.setAccount(tBRaterRegistration.getAccount());
			userInfo.setPwd(tBRaterRegistration.getPwd());
			userInfo.setUpdateUser(returnSessionObj(request).getAccount());
			userInfo.setState(Constants.portal.userState.state_0);
			userInfoDao.update(userInfo);
			
			// 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
	                // 转存文件  
	                file.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                tBRaterRegistration.setPhoto(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
			
			tBRaterRegistration.setUpdateUser(returnSessionObj(request).getAccount());
			tBRaterRegistration.setStatus(StatusEnum.TYPE1.getValue());
			tBRaterRegistrationDao.update(tBRaterRegistration);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("Ids") String Ids){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(","))
		{
			tBRaterRegistrationDao.deleteById(Integer.parseInt(id));
		}
		
		return "@"+jo.toString();
	}
}
